<?php

namespace App\Http\Controllers\Backend\Knowledge;

use App\Models\Access\User\User;
use App\Models\Flaw\Category;
use App\Models\Knowledge\KnowledgeMsg;
use App\Models\SysConfig\SysConfig;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Knowledge\Knowledge;

class KnowledgeController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('access.routeNeedsPermission:knowledge-detail')->only('show');
        //inject access
        $this->middleware('access.routeNeedsPermission:knowledge-add')->only('store');
        $this->middleware('access.routeNeedsPermission:knowledge-update')->only('update');
        $this->middleware('access.routeNeedsPermission:knowledge-settop')->only('setTop');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $pageNum = 10;
        $category = new Category;
        $categories = $category->getCategoryInfo();
        return view('backend.knowledge.index',['pageNum'=>$pageNum,'categoriesJson' =>json_encode($categories)]);
    }

    /**
     * search a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function search(Request $request)
    {
        $knowledge = new knowledge();
        $where = ['category_id'=>$request->category_id,'keywords'=>$request->keywords];
        $sel = ['knowledge.*','users.name as user_name'];
        $klg = $knowledge->lists($sel,$where,[$request->start,$request->length]);
        //总数
        $count = $klg['count'];
        $data = array('draw'=>$request->draw,'recordsTotal'=>$count,'recordsFiltered'=>$count,'data'=>$klg['list']);

        return response()->json($data);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $category = new Category;
        $categories = $category->getCategoryInfo();
        return view('backend.knowledge.add',['categories'=>$categories]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $knowledge = new knowledge();
        $validator = $knowledge->validate($request);
        if ($validator->fails()) {
            return redirect('admin/knowledge/create')
                ->withErrors($validator)
                ->withInput();
        }
        try{

            $knowledge->store($request);
        }catch (\Exception $e){
            \Log::info($e->getMessage());
        }
        return redirect('admin/knowledge');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Knowledge\Knowledge  $knowledge
     * @return \Illuminate\Http\Response
     */
    public function show(Knowledge $knowledge)
    {
        //每次进入刷新浏览量
        $knowledge->updateViews();
        $category = new Category;
        $categories = $category->getCategoryInfo();
        foreach ($categories as $category){
            if ($category->id == $knowledge->category_id)
                $knowledge->category = $category->name;
        }
        return view('backend.knowledge.show',['categories'=>$categories,'knowledge'=>$knowledge]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Knowledge\Knowledge  $knowledge
     * @return \Illuminate\Http\Response
     */
    public function edit(Knowledge $knowledge)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Knowledge\Knowledge  $knowledge
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Knowledge $knowledge)
    {
        $validator = $knowledge->validate($request);
        if ($validator->fails()) {
            return redirect('admin/knowledge/'.$knowledge->id)
                ->withErrors($validator)
                ->withInput();
        }
        try{
            $knowledge->updateRow($request);
        }catch (\Exception $e){
            \Log::info($e->getMessage());
        }
        return redirect('admin/knowledge');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Knowledge\Knowledge  $knowledge
     * @return \Illuminate\Http\Response
     */
    public function destroy(Knowledge $knowledge)
    {
        //
    }

    /**
     * show page
     */
    public function showPage (Request $request){
        $msg = new KnowledgeMsg();
        $klg = Knowledge::find($request->id);
        //发布人
        $klg->publisher = User::find($klg->user_id);
        //分类
        $klg->categoriesCollect = Category::whereIn('id',explode(',',$klg->category_id))->get();
        $klg->categories = $klg->categoriesCollect->implode('name',',');
        $klg->msg = $msg->getMsg($request);
        return view('backend.knowledge.showpage',['klg'=>$klg]);
    }
    /**
     * add comment
     */
    public function addComment (Request $request){
        $ret = ['code'=>0,'msg' => ''];
        $msg = new KnowledgeMsg();
        $validator =$msg->validate($request);
        if ($validator->fails()){
            $error = $validator->errors();
            $ret['code'] = 403;
            $ret['msg']  = $error->first();
        }else{

            try{
                $msg->store($request);
            }catch (\Exception $e){
                $ret['code'] = $e->getCode();
                $ret['msg']  = $e->getMessage();
            }

        }
        return response()->json($ret);
    }

    /**
     * 置顶
     */
    public function setTop(Request $request){
        $msg = new KnowledgeMsg();
        $where = ['module' => 'base'];
        $config = SysConfig::where($where)->first();
        $configJson = json_decode($config->setting);
        $setTopNum = isset($configJson->set_top_num) ? intval($configJson->set_top_num) : 0;
        $topNum = KnowledgeMsg::where(['top'=>1,'klg_id'=>intval($request->kid)])->count();
        if ($topNum > $setTopNum){
            return back()->withErrors('请在系统设置里面设置置顶项！');
        }
        if ($msg->setTop($request)) {
            return back();
        }else{
            return back()->withErrors('服务器忙！');
        }
    }
}
